import { Col, Popconfirm, Form, Row, InputNumber, Image, message, Radio } from "antd";
import CommonImgsLoad from "@/components/CommonImgsLoad";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { CommonTable } from "@/pages/OrderModule/common/components/CommonTable";
import { Input, CommonInput, CommonInputNumber } from "@/views/components/PrefixPlaceholder";
import { DeleteOutlined } from "@ant-design/icons";
import { useState, useEffect, useCallback } from "react";
import { cloneDeep } from "lodash";
import { NumText } from "@/pages/OrderModule/common/components/CommonText";
import { SPU_STATUS } from "@/views/utils/constant";
import React, { useImperativeHandle, forwardRef } from "react";

const defaultSum = {
	retailPrice: 0,
	costPrice: 0,
	purchasePrice: 0,
	weight: 0
};
const CombForm = forwardRef(
	({ parentFormData, sonGoodsList, onDelete, onChange, formData, formIndex, onFormFinish, isOpen }, ref) => {
		const [form] = Form.useForm();
		// const goodsImage = Form.useWatch("image", form);
		const [skuNumList, setSkuNumList] = useState(sonGoodsList);
		const [sum, setSum] = useState(defaultSum);
		const goodsImage = parentFormData?.image;

		useEffect(() => {
			const obj = cloneDeep(defaultSum);
			skuNumList.forEach(e => {
				const num = Number(e.num || 1);
				obj.retailPrice = obj.retailPrice + Number(e.retailPrice || 0) * num;
				obj.costPrice = obj.costPrice + Number(e.costPrice || 0) * num;
				obj.purchasePrice = obj.purchasePrice + Number(e.purchasePrice || 0) * num;
				obj.weight = obj.weight + Number(e.weight || 0) * num;
			});
			setSum(obj);
			if (obj.purchasePrice) {
				form.setFieldValue("purchasePrice", obj.purchasePrice);
			}
			if (obj.weight) {
				form.setFieldValue("weight", obj.weight);
			}
			if (obj.retailPrice) {
				form.setFieldValue("retailPrice", obj.retailPrice);
			}
			if (obj.costPrice) {
				form.setFieldValue("costPrice", obj.costPrice);
			}
		}, [skuNumList]);

		useEffect(() => {
			form.setFieldsValue(parentFormData);
			console.log(parentFormData, "parentFormData");
		}, []);

		const onFinish = useCallback(
			v => {
				const data = cloneDeep(v);
				data["combinations"] = skuNumList.map(e => ({ skuId: e.id, num: e.num ? e.num : 1 }));
				onFormFinish(data, formIndex);
			},
			[skuNumList]
		);
		// 图片上传失败
		const handleError = (err, failed) => {
			// console.log("file upload error", err, failed);
			if (!err.isLt2M) {
				Modal.error({ content: "图片仅限1m以内，上传失败", centered: true });
			}
		};
		const handleUploadImg = useCallback(
			val => {
				form.setFieldsValue({
					image: val
				});
			},
			[form]
		);
		const handleNumChange = (e, record, index) => {
			const val = typeof e === "number" ? e : e ? e.target.value : 1;
			const reg = /^[1-9]\d*$/;
			if (reg.test(val)) {
				setSkuNumList(pre => {
					pre[index].num = val;
					return cloneDeep(pre);
				});
			} else {
				message.info("请输入正整数");
			}
		};
		const confirm = async item => {
			setSkuNumList(pre => {
				return cloneDeep(pre.filter(e => e.id !== item.id));
			});
			message.success("删除操作成功");
		};

		const columns = [
			{
				title: "图片",
				dataIndex: "image",
				render: (value, record, i) => <Image width={60} src={value} />
			},
			{
				title: "商品名称",
				dataIndex: "skuName"
			},
			{
				title: "商品编码",
				dataIndex: "skuCode"
			},
			{
				title: "零售价",
				dataIndex: "retailPrice",
				render: value => value && <NumText as="s1" pre="¥" num={value} />
			},
			{
				title: "成本价",
				dataIndex: "costPrice",
				render: value => value && <NumText as="s1" pre="¥" num={value} />
			},
			{
				title: "市场价",
				dataIndex: "tagPrice",
				render: value => value && <NumText as="s1" pre="¥" num={value} />
			},
			{
				title: "采购价",
				dataIndex: "purchasePrice",
				render: value => value && <NumText as="s1" pre="¥" num={value} />
			},
			{
				title: "重量",
				dataIndex: "weight",
				render: value => value && <NumText as="s1" suffix="kg" num={value} />
			},
			{
				title: "数量",
				dataIndex: "num",
				render: (text, record, index) => (
					<div>
						<InputNumber
							min={1}
							value={text}
							precision={0}
							onBlur={e => handleNumChange(e, record, index)}
							onChange={e => handleNumChange(e, record, index)}
							controls={false}
						/>
					</div>
				)
			},
			{
				title: "商品成本",
				dataIndex: "productIngredients"
			},
			{
				name: "自定义属性",
				dataIndex: "customAttribute"
			},
			{
				title: "操作",
				dataIndex: "index",
				lock: true,
				render: (t, r, i) => (
					<span className="opera-span-common">
						<Popconfirm title="确定删除该条数据?" onConfirm={() => confirm(r)}>
							<a href="#" disabled={r.isDefault == 0}>
								删除
							</a>
						</Popconfirm>
					</span>
				),
				width: 180
			}
		];

		useImperativeHandle(ref, () => ({
			// 暴露给父组件的方法
			submit: () => {
				form.submit();
			}
		}));
		return (
			<Form form={form} onFinish={onFinish}>
				<div style={{ display: "flex", justifyContent: "space-between" }}>
					<SubTitle symbol as="s2" title={`组合 (${formIndex + 1})`} wrapStyle={{ marginBottom: 16 }} />
					<div onClick={() => onDelete(formIndex)}>
						<DeleteOutlined style={{ color: "red" }} />
						<a>删除</a>
					</div>
				</div>
				<>
					<Row gutter={[12, 6]} id="basic-data">
						<Col span={12}>
							<Form.Item name="skuName" rules={[{ required: true, message: "请输入商品名称" }]}>
								<CommonInput placeholder="商品名称" aria-required showCount maxLength={100} />
							</Form.Item>
						</Col>
						<Col span={6}>
							<Form.Item name="skuCode" rules={[{ required: true, message: "组合编码" }]}>
								<CommonInput Component={Input} placeholder="组合编码" aria-required showCount maxLength={200} />
							</Form.Item>
						</Col>
					</Row>

					<Row gutter={[12, 6]}>
						<Col span={24}>组合商品图片</Col>
						<Col span={24}>
							<Form.Item name="image">
								<div className="flex">
									<div>
										<CommonImgsLoad img={goodsImage} handleOk={handleUploadImg} handleError={handleError} upLoadText="请上传" />
									</div>
									<span className="ml8" style={{ color: "rgba(177, 183, 195, 1)" }}>
										图片建议与第三方平台保存一致
									</span>
								</div>
							</Form.Item>
						</Col>
					</Row>
					<Row gutter={[12, 6]}>
						<Col span={6}>
							<Form.Item name="retailPrice">
								<CommonInputNumber min={0} placeholder="零售价" precision={2} controls={false} />
							</Form.Item>
						</Col>
						<Col span={6}>
							<Form.Item name="costPrice" rules={[{ required: true, message: "请输入" }]}>
								<CommonInputNumber min={0} placeholder="成本价" precision={2} controls={false} />
							</Form.Item>
						</Col>
						<Col span={6}>
							<Form.Item name="purchasePrice">
								<CommonInputNumber min={0} placeholder="采购价" disabled precision={2} controls={false} />
							</Form.Item>
						</Col>
						<Col span={6}>
							<Form.Item name="virtualInventory">
								<CommonInputNumber min={0} placeholder="虚拟库存" disabled precision={2} controls={false} />
							</Form.Item>
						</Col>
						<Col span={6}>
							<Form.Item name="price1">
								<CommonInputNumber min={0} placeholder="其他价格1" disabled precision={2} controls={false} />
							</Form.Item>
						</Col>
						<Col span={6}>
							<Form.Item name="price2">
								<CommonInputNumber min={0} placeholder="其他价格2" disabled precision={2} controls={false} />
							</Form.Item>
						</Col>
						<Col span={6}>
							<Form.Item name="price3">
								<CommonInputNumber min={0} placeholder="其他价格3" disabled precision={2} controls={false} />
							</Form.Item>
						</Col>
						<Col span={6}>
							<Form.Item name="attribute1">
								<CommonInput placeholder="其他属性1" showCount maxLength={50} />
							</Form.Item>
						</Col>
						<Col span={6}>
							<Form.Item name="attribute2">
								<CommonInput placeholder="其他属性2" showCount maxLength={50} />
							</Form.Item>
						</Col>
						<Col span={6}>
							<Form.Item name="attribute3">
								<CommonInput placeholder="其他属性3" showCount maxLength={50} />
							</Form.Item>
						</Col>
					</Row>
					<Row gutter={[12, 6]}>
						<Col span={24}>
							<Form.Item label="商品状态" name="status">
								<Radio.Group defaultValue={0}>
									{SPU_STATUS.map(item => (
										<Radio key={item.value} value={item.value}>
											{item.label}
										</Radio>
									))}
								</Radio.Group>
							</Form.Item>
						</Col>
					</Row>
					<Row gutter={[12, 6]}>
						<Col span={6}>
							<Form.Item label="子商品零售总价：">
								<div style={{ color: "rgba(240, 61, 41, 1)" }}>￥{sum.retailPrice}</div>
							</Form.Item>
						</Col>
						<Col span={6}>
							<Form.Item label="子商品成本总价：">
								<div style={{ color: "rgba(240, 61, 41, 1)" }}>￥{sum.costPrice}</div>
							</Form.Item>
						</Col>
						<Col span={6}>
							<Form.Item label="子商品采购总价：">
								<div style={{ color: "rgba(240, 61, 41, 1)" }}>￥{sum.purchasePrice}</div>
							</Form.Item>
						</Col>
						<Col span={6}>
							<Form.Item label="子商品总重量：">
								<div style={{ color: "rgba(240, 61, 41, 1)" }}>￥{sum.weight}</div>
							</Form.Item>
						</Col>
						<CommonTable scroll={{ y: `calc(100vh - 250px)` }} columns={columns} dataSource={skuNumList} pagination={false} />
					</Row>
				</>
			</Form>
		);
	}
);

export default CombForm;
